<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="分数" prop="score">
        <el-input v-model="queryParams.score" placeholder="请输入分数" clearable size="small"
          @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="排序" prop="sort">
        <el-input v-model="queryParams.sort" placeholder="请输入排序" clearable size="small"
          @keyup.enter.native="handleQuery" />
      </el-form-item>

      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
          v-hasPermi="['generator:question:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate"
          v-hasPermi="['generator:question:edit']">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['generator:question:remove']">删除</el-button>
      </el-col>

      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="questionList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="题干" align="center" prop="content" />
      <el-table-column label="分数" align="center" prop="score" />
      <el-table-column label="题目类型" align="center" prop="type">
        <template slot-scope="scope">
          <div v-if="scope.row.type==0">单选</div>
          <div v-if="scope.row.type==1">多选</div>
          <div v-if="scope.row.type==2">填空</div>
          <div v-if="scope.row.type==4">简答</div>
        </template>
      </el-table-column>
      <el-table-column label="排序" align="center" prop="sort" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
            v-hasPermi="['generator:question:edit']">修改</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
            v-hasPermi="['generator:question:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />

    <!-- 添加或修改题目对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="题干">
          <el-input v-model="form.content" placeholder="请输入题干" type="textarea" />
        </el-form-item>
        <el-form-item label="题目解析">
          <el-input v-model="form.solution" placeholder="请输入题目解析" type="textarea" />
        </el-form-item>
        <el-form-item label="分数" prop="score">
          <el-input v-model="form.score" placeholder="请输入分数" />
        </el-form-item>
        <el-form-item label="排序" prop="sort">
          <el-input v-model="form.sort" placeholder="请输入排序" />
        </el-form-item>

        <el-form-item label="题目类型" prop="type">

          <el-radio label="0" v-model="form.type">单选</el-radio>
          <el-radio label="1" v-model="form.type">多选</el-radio>
          <el-radio label="2" v-model="form.type">填空</el-radio>
          <el-radio label="4" v-model="form.type">简答</el-radio>
        </el-form-item>

        <el-form-item label="选项设置" prop="set" v-if="form.type==1||form.type==0">
          <div class="prize-set">
            <div class="ps-top">
              <div>
                <template v-for="(item,index) in prizeSetList">
                  <span class="ps-single small-btn" :class="chooseIdx==index+1?'ps-single-active':''"
                    @click="toChangeIdx(index+1)">选项{{index+1}}</span>
                </template>
              </div>

              <div class="prize-change">
                <i class="el-icon-minus small-btn" @click="toChangePrizeNum(0)"></i>
                <i class="el-icon-plus small-btn" @click="toChangePrizeNum(1)"></i>
              </div>
            </div>
            <el-form class="single-prize demo-ruleForm" :model="prizeSetList[chooseIdx-1]" ref="prizeSetList"
              label-width="100px">

              <el-checkbox label="0" v-model="prizeSetList[chooseIdx-1].isRight">
                <el-input v-model="prizeSetList[chooseIdx-1].optionContent">
                </el-input>
              </el-checkbox>
            </el-form>
          </div>
        </el-form-item>

        <el-form-item label="答案" prop="set" v-if="form.type==2||form.type==4">
          <div class="prize-set">
            <el-form class="single-prize demo-ruleForm" :model="prizeSetList[chooseIdx-1]" ref="prizeSetList"
              label-width="100px">
              <el-input v-model="prizeSetList[chooseIdx-1].content" type="textarea" v-if="form.type==2"></el-input>
              <el-input v-model="prizeSetList[chooseIdx-1].shortAnswer" type="textarea" v-if="form.type==4"></el-input>
            </el-form>
          </div>
        </el-form-item>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listQuestion, getQuestion, delQuestion, addQuestion, updateQuestion } from "@/api/generator/question";

export default {
  name: "Question",
  data () {
    return {
      ifsure: "",

      prizeSetList: [{
        optionId: "",
        optionContent: "",
        questionId: "",
        shortAnswer: "",
        isRight: "0",
        content: ""
      }],
      chooseIdx: 1,
      singlePrize: {
        optionId: "",
        optionContent: "",
        questionId: "",
        shortAnswer: "",
        isRight: "0",
        content: ""
      },

      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 题目表格数据
      questionList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        content: null,
        score: null,
        type: null,
        sort: null,
        paperId: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
      }
    };
  },
  created () {
    this.getList();
  },
  methods: {
    /** 查询题目列表 */
    getList () {
      this.loading = true;
      listQuestion(Object.assign(this.queryParams, { paperId: this.$route.query.id })).then(response => {
        this.questionList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel () {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset () {
      this.form = {
        id: null,
        content: null,
        score: null,
        type: "0",
        sort: null,
        paperId: null
      };
      this.prizeSetList = [{
        optionId: "",
        optionContent: "",
        questionId: "",
        shortAnswer: "",
        isRight: "0",
        content: ""
      }]
      this.chooseIdx = 1
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery () {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery () {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange (selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd () {
      this.reset();
      this.open = true;
      this.title = "添加题目";
    },
    /** 修改按钮操作 */
    handleUpdate (row) {
      this.reset();
      const id = row.id || this.ids
      getQuestion(id).then(response => {
        this.form = response.data;

        if (response.data.optionList != "") {
          this.prizeSetList = response.data.optionList
          for (var i = 0; i < response.data.optionList.length; i++) {
            if (response.data.optionList[i].isRight == 0) {
              response.data.optionList[i].isRight = false
            } else {
              response.data.optionList[i].isRight = true
            }
          }
        }

        this.form.type = response.data.type + ""
        this.open = true;
        this.title = "修改题目";
      });
    },
    /** 提交按钮 */
    submitForm () {
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.form.paperId = this.$route.query.id
          for (var i = 0; i <= this.prizeSetList.length - 1; i++) {
            // this.prizeSetList[i].optionId = this.form.optionList[i].optionId
            this.prizeSetList[i].questionId = this.form.id

          }
          let isTrue = this.prizeSetList.filter(item => {
            return item.isRight == true
          })

          if (isTrue.length == 1) {
            this.ifsure = true
          } else {
            this.ifsure = false
          }

          if (this.ifsure == true || this.type != 0) {
            for (var i = 0; i <= this.prizeSetList.length - 1; i++) {
              if (this.prizeSetList[i].isRight == false) {
                this.prizeSetList[i].isRight = 0
              } else if (this.prizeSetList[i].isRight == true) {
                this.prizeSetList[i].isRight = 1
              }
            }
            this.form.optionList = this.prizeSetList
            if (this.form.id != null) {
              updateQuestion(this.form).then(response => {
                this.$modal.msgSuccess("修改成功");
                this.open = false;
                this.getList();
              });
            } else {
              addQuestion(this.form).then(response => {
                this.$modal.msgSuccess("新增成功");
                this.open = false;
                this.getList();
              });
            }
          } else {
            this.ifsure = false
            this.$modal.msgError("请重新设置答案");
          }

        }
      });
    },


    /** 删除按钮操作 */
    handleDelete (row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除题目编号为"' + ids + '"的数据项？').then(function () {
        return delQuestion(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => { });
    },

    // 添加删除选项
    toChangePrizeNum (value) {
      if ((this.prizeSetList.length == 1 && value == 0)) {
        this.$message("请至少留一个选项")
        return
      }
      if (value == 0) {
        this.prizeSetList.splice(this.chooseIdx - 1, 1)
        if (this.chooseIdx == this.prizeSetList.length + 1) {
          this.chooseIdx--
        }
        this.prizeSetList.map((item, idx) => {
          // item.chooseIdx = idx + 1
          item.name = '选项' + (idx + 1)
        })
      } else {
        this.chooseIdx++
        this.toUpdatePrize(this.prizeSetList.length + 1)
      }
    },

    // 选项数组更改
    toUpdatePrize (idx) {
      // this.singlePrize.chooseIdx = idx
      let single = JSON.stringify(this.singlePrize)
      let singleStr = JSON.parse(single)
      this.prizeSetList.push(singleStr)
    },
    // 切换选项
    toChangeIdx (idx) {
      this.chooseIdx = idx
    },

  }
};
</script>


<style scoped>
.small-btn {
  display: inline-block;
  height: 32px;
  line-height: 32px;
  text-align: center;
  border-radius: 5px;
  background-color: #fafafa;
  margin-right: 12px;
}
.prize-set {
  width: 80%;
  background-color: #fafafa;
}

.ps-top {
  /* height: 40px; */
  display: flex;
  justify-content: space-between;
  background-color: #d9d9d9;
  padding: 12px;
  align-items: center;
  cursor: pointer;
}

.prize-change > i {
  width: 32px;
  margin: 0 0 0 12px;
}

.ps-single {
  width: 60px;
}

.ps-single-active {
  background-color: #409eff;
  color: #fff;
}

.single-prize {
  padding: 12px 20px;
}

/deep/ .single-prize .el-input {
  width: 50%;
}

/deep/ .single-prize .el-form-item {
  margin-bottom: 8px;
}
</style>